<?php

/**
 * @author      :   Nhanva
 * @name        :   Match
 * @copyright   :   Fpt Online
 * @todo        :   Match model
 */
class Match
{

    protected static $_instance = null;

    const MATCH_HOT_DETAIL = 'match_hot_detail';
    const MATCHES_IN_WEEK  = 'matches_in_week_list';
    const MATCH_DETAIL     = 'match_detail';
    const MATCHES_TIME     = 'match_time_list';
    const MATCHES_SEASON_LEAGUE = 'matches_season_league_list';

    /**
     * Constructor of class
     * we don't permit an explicit call of the constructor! (like $v = new Singleton())
     */
    protected function __construct ()
    {
        
    }

    /**
     * Get singletom instance
     * @return Match
     */
    public final static function getInstance ()
    {
        //Check instance
        if (is_null(self::$_instance))
        {
            self::$_instance = new self();
        }

        //Return instance
        return self::$_instance;
    }

    /**
     * Get hot match info
     * @param type $arrParams
     * @author  : nhanva@fpt.net 
     */
    public function getHotMatch ($strPosition, $intCategory)
    {
        $arrHotMatch = array ();
        try
        {
            // Build key cache
            $keyCache = Fpt_Global::makeCacheKey(self::MATCH_HOT_DETAIL, array ($strPosition, $intCategory));

            // Get instance memcache
            $memcacheInstance = Fpt_Global::getMemcacheInstance($intCategory);

            // Read hot match in memcache
            //$arrHotMatch = $memcacheInstance->read($keyCache);

            if (empty($arrHotMatch))
            {
                $matchMysql = Fpt_Business_Match::getInstance(array ('adapter' => 'mysql'));

                // Get data in DB
                $arrHotMatch = $matchMysql->getHotMatch($strPosition, $intCategory);
                if (!empty($arrHotMatch))
                {
                    // Store into cache
//                    $memcacheInstance->write($keyCache, $arrHotMatch);
                    Fpt_Global::writeMemcache($intCategory, $keyCache, $arrHotMatch);
                }
            }
        }
        catch (Exception $ex)
        {
            //log error
            Fpt_Log::sendlog(4, $ex->getCode(), $ex->getMessage(), $ex->getTraceAsString(), null, null);
        }
        return $arrHotMatch;
    }

    /**
     * Get list matches happen in week
     * @param int $seasonId
     * @param int $leagueId
     * @param int $beginDate
     * @param int $endDate
     * @return array|boolean 
     * @author QuangTM
     */
    public function getMatchInWeek ($seasonId, $leagueId, $beginDate, $endDate)
    {
        $memcacheInstance = Fpt_Global::getMemcacheInstance($seasonId + $leagueId);
        $keyCache         = Fpt_Global::makeCacheKey(self::MATCHES_IN_WEEK, array ($leagueId, $seasonId, $beginDate, $endDate));
        // Read cache
        $listMatches = $memcacheInstance->read($keyCache);
        // If miss cache
        if ($listMatches === FALSE)
        {
            try
            {
                $config   = Fpt_Global::getApplicationIni();
                // Get db teamseason instance
                $matchObj = Fpt_Business_Match::getInstance($config['database']['default']);

                // Get data from db
                $listMatches = $matchObj->getMatchInWeek($seasonId, $leagueId, $beginDate, $endDate);

                // Write to cache
                if(count($listMatches))
                    Fpt_Global::writeMemcache($seasonId + $leagueId, $keyCache, $listMatches);
                else
                    Fpt_Global::writeMemcache($seasonId + $leagueId, $keyCache, -1);
            }
            catch (Zend_Exception $ex)
            {
                Fpt_Log::sendlog(4, $ex->getCode(), $ex->getMessage(), $ex->getTraceAsString(), null, null);
                return FALSE;
            }
        }
        else if($listMatches == -1)
        {
            return array();
        }
        return $listMatches;
    }

    /**
     * Get list matches by ids
     * @param array $arrMatchIDs
     * @return array 
     * @author QuangTM
     */
    public function getMatchDetailByIDs (array $arrMatchIDs)
    {
        $result = array ();
        $arrMissCache = array ();
        foreach ($arrMatchIDs as $matchID)
        {
            $memcacheInstance = Fpt_Global::getMemcacheInstance($matchID);
            $keyCache         = Fpt_Global::makeCacheKey(self::MATCH_DETAIL, $matchID);
            $matchDetail      = $memcacheInstance->read($keyCache);
            if ($matchDetail === FALSE)
            {
                array_push($arrMissCache, $matchID);
            }
            else
            {
                array_push($result, $matchDetail);
            }
        }

        // If miss some items
        if (count($arrMissCache))
        {
            // Get config 
            $config = Fpt_Global::getApplicationIni();

            // Get DB Obj
            $matchObj = Fpt_Business_Match::getInstance($config['database']['default']);
            
            // Get multi article
            $arrMissMatches = $matchObj->getMatchDetailByIDs($arrMissCache);

            // Write memcache for each
            foreach ($arrMissMatches as $matchDetail)
            {
                $keyCache         = Fpt_Global::makeCacheKey(self::MATCH_DETAIL, $matchDetail['MatchID']);
                Fpt_Global::writeMemcache($matchDetail['MatchID'], $keyCache, $matchDetail);
            }

            $result = array_merge($result, $arrMissMatches);
        }
        return $result;
    }

    /**
     * Get list matches by happen time
     * @param int $unixTime
     * @return array 
     * @author QuangTM
     */
    public function getMatchIDsHappenTime ($unixTime, $leagueID = NULL)
    {
        $memcacheInstance = Fpt_Global::getMemcacheInstance($unixTime);
        $keyCache         = Fpt_Global::makeCacheKey(self::MATCHES_TIME, array ($unixTime, intval($leagueID)));
        // Read cache
        $listMatches = $memcacheInstance->read($keyCache);
        
        // If miss cache
        if ($listMatches === FALSE)
        {
            try
            {
                $begin = $unixTime;
                $end   = $unixTime + 86399; // 23:59:59

                $config   = Fpt_Global::getApplicationIni();
                // Get db teamseason instance
                $matchObj = Fpt_Business_Match::getInstance($config['database']['default']);

                // Get data from db
                $listMatches = $matchObj->getListMatchesByHappenTime($begin, $end, $leagueID);

                // Write to cache
                if (count($listMatches))
                    Fpt_Global::writeMemcache($unixTime, $keyCache, $listMatches);
                else
                    Fpt_Global::writeMemcache($unixTime, $keyCache, -1);
            }
            catch (Zend_Exception $ex)
            {
                Fpt_Log::sendlog(4, $ex->getCode(), $ex->getMessage(), $ex->getTraceAsString(), null, null);
                return FALSE;
            }
        }
        else if ($listMatches == -1)
            return array();
        return $listMatches;
    }

    /**
     * Get array match ids by happen time and array league ids
     * @param int $unixTime
     * @param array $arrLeagueIDs
     * @return array
     * @author QuangTM 
     */
    public function getMatchIDsHappenTimeByLeagueIDs(int $unixTime, array $arrLeagueIDs)
    {
        if(!is_array($arrLeagueIDs) || !count($arrLeagueIDs))
            return $this->getMatchIDsHappenTime ($unixTime, NULL);
        else
        {
            $result = array();
            foreach ($arrLeagueIDs as $leagueID)
                $result = array_merge($result, $this->getMatchIDsHappenTime($unixTime, $leagueID));
            return $result;
        }
    }
     
    
    public function getMatchIDsBySeasonAndLeague($seasonID,$leagueID)
    {
        $memcacheInstance = Fpt_Global::getMemcacheInstance($seasonID + $leagueID);
        $keyCache         = Fpt_Global::makeCacheKey(self::MATCHES_SEASON_LEAGUE, array ($seasonID,$leagueID));
        // Read cache
        //$memcacheInstance->delete($keyCache);exit;
        $listMatcheIDs = $memcacheInstance->read($keyCache);        
        $listMatcheIDs = FALSE;
        // If miss cache
        if ($listMatcheIDs === FALSE)
        {             
            try
            {
                $config   = Fpt_Global::getApplicationIni();
                // Get db teamseason instance
                $matchObj = Fpt_Business_Match::getInstance($config['database']['default']);

                // Get data from db
                $listMatcheIDs = $matchObj->getMatchIDsBySeasonAndLeague($seasonID, $leagueID);
                
                // Write to cache
                if (count($listMatcheIDs))
                    Fpt_Global::writeMemcache($unixTime, $keyCache, $listMatcheIDs);
                else
                    Fpt_Global::writeMemcache($unixTime, $keyCache, -1);
            }
            catch (Zend_Exception $ex)
            {
                Fpt_Log::sendlog(4, $ex->getCode(), $ex->getMessage(), $ex->getTraceAsString(), null, null);
                return FALSE;
            }
        }
        else if ($listMatcheIDs == -1)
            return array();
        return $listMatcheIDs;
    }
}